package com.pingan.haofang.searchcloud.common.validator;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.pingan.haofang.framework.common.functional.lang.control.base.Enums;
import com.pingan.haofang.searchcloud.common.validator.annotation.EnumOption;

/**
 * 枚举校验器
 *
 * @author LUYI374
 * @date 2017年3月2日
 * @since 1.0.0
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class EnumOptionValidator implements ConstraintValidator<EnumOption, Object> {

    /**
     * 额外附加选项
     */
    private Set<Object> addition;

    /**
     * ENUM类型
     */
    private Class enumClass;

    /**
     * 排除列表
     */
    private Set<Object> excludes;

    @Override
    public void initialize(EnumOption option) {
        Class<? extends Enum<?>> enumClass = option.enumClass();
        this.enumClass = enumClass;
        if (option.additionValues() != null && option.additionValues().length > 0) {
            this.addition = new HashSet<>(option.additionValues().length);
            for (int item : option.additionValues()) {
                this.addition.add(item);
            }
        } else {
            this.addition = new HashSet<>(0);
        }

        if (option.excludeValues() != null && option.excludeValues().length > 0) {
            this.excludes = new HashSet<>(option.excludeValues().length);
            for (int item : option.excludeValues()) {
                this.excludes.add(item);
            }
        } else {
            this.excludes = new HashSet<>(0);
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        } else {
            Optional optional = Enums.find(value, enumClass);
            if (!optional.isPresent()) {
                return addition.contains(value);
            } else {
                return !excludes.contains(value);
            }
        }
    }

}
